import 'package:flutter/material.dart';
import 'package:flutter_smart_heating/common/event.dart';
import 'package:flutter_smart_heating/common/http.dart';
import 'package:flutter_smart_heating/mode/list_pagination_model.dart';
import 'package:flutter_smart_heating/ui/src/pull_to_refresh.dart';
import 'package:flutter_smart_heating/ui/ui.dart';
import 'package:get/get.dart';

class ComplainPage extends StatefulWidget {
  const ComplainPage({super.key});

  @override
  State<ComplainPage> createState() => _ComplainPageState();
}

class _ComplainPageState extends State<ComplainPage>
    with SingleTickerProviderStateMixin {
  late TabController tabController;
  dynamic eventBus;
  @override
  void initState() {
    super.initState();
    eventBus =
        AppEvent().eventBus.on<RootNavigateChangeEvent>().listen((event) {
      if (event.name == 'service') {
        if (Get.parameters['type'] != null) {
          tabController.index = int.tryParse(Get.parameters['type']!) ?? 0;
        }
      }
    });
    int initialIndex = 0;
    if (Get.parameters['type'] != null) {
      initialIndex = int.tryParse(Get.parameters['type']!) ?? 0;
    }
    tabController = TabController(
      length: 2,
      vsync: this,
      initialIndex: initialIndex,
    );
  }

  @override
  void dispose() {
    eventBus.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: UiPanel(
          width: 200,
          borderRadius: BorderRadius.circular(30),
          height: 35,
          child: TabBar(
            controller: tabController,
            isScrollable: false,
            dividerColor: Colors.transparent,
            splashBorderRadius: BorderRadius.circular(30),
            indicatorSize: TabBarIndicatorSize.tab,
            indicator: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(30),
              gradient: const LinearGradient(
                colors: [
                  Color.fromARGB(255, 11, 232, 248),
                  Color.fromARGB(255, 33, 51, 243),
                ],
              ),
            ),
            indicatorColor: Colors.black,
            labelColor: Colors.white,
            unselectedLabelColor:
                UiTheme(context).matchColor(Colors.black, Colors.white),
            unselectedLabelStyle: const TextStyle(
              fontWeight: FontWeight.normal,
            ),
            labelStyle: TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: UiTheme.fontSize.tabbarFontSize,
              color: Colors.red,
            ),
            tabs: const [
              Tab(
                text: "投诉信息",
              ),
              Tab(
                text: "故障信息",
              ),
            ],
          ),
        ),
      ),
      body: TabBarView(
        controller: tabController,
        children: [
          pageView(0),
          pageView(1),
        ],
      ),
    );
  }

  Widget pageView(type) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: UiTheme.spacingX),
      child: Column(
        children: [
          const SizedBox(height: UiTheme.toolbarSpacing),
          const UiPanel(
            height: 40,
            child: Row(children: [
              SizedBox(
                  width: 120,
                  child: Text(
                    '日期',
                    textAlign: TextAlign.center,
                  )),
              Expanded(
                  child: Text(
                '来源',
                textAlign: TextAlign.center,
              )),
              Expanded(
                child: Text(
                  '数量',
                  textAlign: TextAlign.center,
                ),
              ),
              SizedBox(
                width: 80,
                child: Text(
                  '年份',
                  textAlign: TextAlign.center,
                ),
              )
            ]),
          ),
          Expanded(
            child: FeedbackPageItemView(type: type),
          ),
        ],
      ),
    );
  }
}

class FeedbackPageItemView extends StatefulWidget {
  const FeedbackPageItemView({super.key, this.type});
  final int? type;

  @override
  State<FeedbackPageItemView> createState() => _FeedbackPageItemViewState();
}

class _FeedbackPageItemViewState extends State<FeedbackPageItemView>
    with AutomaticKeepAliveClientMixin {
  List<dynamic> list = List.filled(20, {}).toList();
  ListPaginationModel pagination = ListPaginationModel();
  bool refreshing = false;
  RefreshController refreshController = RefreshController();
  @override
  bool get wantKeepAlive => true;
  @override
  void initState() {
    if (mounted) {
      fetchData();
    }
    super.initState();
  }

  fetchData() async {
    var res = await Http.instance.post(
      '/api/information/${widget.type == 0 ? 'complain' : 'fault'}/index',
      data: {"page": pagination.currentPage},
    );
    if (res.code == 1) {
      if (pagination.currentPage <= 1) {
        list.clear();
      }
      pagination = ListPaginationModel.fromJson(res.data);
      res.data['data'].forEach(
        (item) => list.add(item),
      );
    }
    setState(() {});
    refreshController.refreshCompleted();
    if (pagination.hasMore) {
      refreshController.loadComplete();
    } else {
      refreshController.loadNoData();
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return UiPushToRefresh(
      controller: refreshController,
      onRefresh: () {
        pagination.currentPage = 1;
        fetchData();
      },
      enablePullUp: pagination.lastPage > 1 && !refreshController.isRefresh,
      onLoad: () {
        pagination.currentPage++;
        fetchData();
      },
      child: list.isEmpty
          ? const Center(child: UiResult())
          : ListView.builder(
              padding: const EdgeInsets.only(
                bottom: 10,
                top: 10,
              ),
              itemBuilder: (context, index) {
                var item = list[index];
                if (item['date'] == null) {
                  return Container(
                    alignment: Alignment.center,
                    height: 30,
                    margin: const EdgeInsets.only(bottom: 6),
                    child: const Row(children: [
                      SizedBox(width: 120, child: UiBlock()),
                      SizedBox(width: 10),
                      Expanded(child: UiBlock()),
                      SizedBox(width: 10),
                      Expanded(child: UiBlock()),
                      SizedBox(width: 10),
                      SizedBox(width: 80, child: UiBlock()),
                    ]),
                  );
                }
                return Container(
                  alignment: Alignment.center,
                  height: 40,
                  decoration: BoxDecoration(
                    color: index % 2 == 0
                        ? null
                        : UiTheme.of(context).panelBackground,
                    borderRadius: BorderRadius.circular(
                      UiTheme.boxRadiusX,
                    ),
                  ),
                  child: Row(children: [
                    SizedBox(
                        width: 120,
                        child: Text(
                          '${item['date']}',
                          textAlign: TextAlign.center,
                        )),
                    Expanded(
                        child: Text(
                      Ui.getString(item['source'], '--'),
                      textAlign: TextAlign.center,
                    )),
                    Expanded(
                      child: Text(
                        '${item['count']}',
                        textAlign: TextAlign.center,
                      ),
                    ),
                    SizedBox(
                      width: 80,
                      child: Text(
                        '${item['heating_year']}',
                        textAlign: TextAlign.center,
                      ),
                    )
                  ]),
                );
              },
              itemCount: list.length,
            ),
    );
  }
}
